<?php

session_start();

if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
    $login = "";
    header("Location: login.php");
} else {
    $login = $_SESSION['login'];
}
$errorMessage = "";
$num_rows = 0;
$used = "";
//
include 'i_functions.php';
//
$DataType = $_SESSION['DataType'];
$Data = $_SESSION['Data'];
$Trace = $_SESSION['Trace'];
if ($Trace) {
    print "<br>FormUpdate.php - DataType=" . $DataType . ", Data=";
    var_dump($Data);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //
    $user_name = "root";
    $pass_word = "haddons";
    $database = "PPI";
    $server = "127.0.0.1";

    $db_handle = mysql_connect($server, $user_name, $pass_word);
    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {
//
        $FormID = $_POST['FormID'];
        $ParamID = "params/" . $FormID . ".txt";
        $TableName = $_POST['TableName'];
        $ID = $_POST['ID'];
        //print "<br>FormUpdate.php - ID = " . $ID;
        $field = $_POST['field']; //the field(s) from the HTML Form.
        //
        $UE_Func = $FormID;
        $UE_Code = $UE_Func . ".php";
//
        $SQL1 = "";
        $SQL2 = "";
        //$ParamID = $ParamID . ".csv";
        if (file_exists($ParamID)) {
            if (strpos($ParamID, ".csv")) {
                $dlim = ",";
            } else {
                $dlim = "\t";
            }

            $UE_Opts['Exit'] = "U";
            //$UE_Opts['Trace'] = true;
            //$UE_Func = $ParamID;
            $UE_Code = $UE_Func . ".php";
            if (is_file($UE_Code)) {
                include $UE_Code;
            }
            $ParamFile = fopen($ParamID, "r");
            $i = 0;

            if ($DataType == "txt") {
                if (strpos($TableName, ".csv")) {
                    $dlim2 = ",";
                } else {
                    $dlim2 = "\t";
                }
                if ($ID == "NEW") {
                    $Data[] = $field; //append a new line
                } else {
                    $Data[$ID] = $field; //replace existing line
                }
                //print "<br>FormUpdate.php - Data = ";
                //var_dump($Data);
                $lnct = count($Data);
                //print "<br> lnct = " . $lnct . "<br>EOL = " . ord(PHP_EOL) . "<br>";
                $file_handle = fopen($TableName, "w");
                for ($ln = 0; $ln < $lnct; $ln++) {
                    $Line = implode($dlim2, $Data[$ln]);
                    $len = strlen($Line);
                    $LastChar = substr($Line, $len - 1, 1);
                    if ($LastChar <> PHP_EOL) {
                        $Line = $Line . PHP_EOL;
                    }
                    if ($Trace) {
                        $NewLen = strlen($Line);
                        $NewLastChar = substr($Line, $NewLen - 1, 1);
                        print "<br>Line = " . $Line;
                        print ", length=" . $len . ", LastChar=" . $LastChar . " (" . ord($LastChar) . "), NewLen=" . $NewLen . ", LastChar=" . $NewLastChar . "(" . ord($NewLastChar) . ")";
                    }
                    fwrite($file_handle, $Line);
                }
                fclose($file_handle);
            } else {
                while (!feof($ParamFile)) {
                    $line = fgets($ParamFile);
                    //print "<br>" . $line . $field[$i];
                    $ParamRec = explode($dlim, $line);
                    $FieldType = $ParamRec[1];
                    $Default = $ParamRec[4];
                    $FieldName = $ParamRec[9];
                    $UserExit = $ParamRec[10];
                    if ($Trace) {
                        print "<br>FormUpdate.php - ParamRec=";
                        var_dump($ParamRec);
                    }
                    if ($FieldName) {
                        if ($i == 0) {
                            $ID = quote_smart($field[$i], $db_handle);
                            $SQL1 = "SELECT * FROM $TableName WHERE $FieldName = $ID";
                            $result = mysql_query($SQL1);
                            $num_rows = mysql_num_rows($result);
                            if ($result) {
                                if ($num_rows > 0) {
                                    //print "<br>FormUpdate.php - " . $ID . " on table " . $TableName;
                                    $Action = "U";
                                    $SQL2 = "UPDATE `" . $TableName . "` SET ";
                                    //$SQL2 = $SQL2 . "`" . $FieldName . "` = '" . $field[$i] . "'";
                                } else {
                                    //print "<br>FormUpdate.php - new item";
                                    $Action = "I";
                                    $SQL2 = "INSERT INTO `" . $TableName . "`";
                                    if ($field[$i] <> "") {
                                        $SQL2_Cols = "`" . $FieldName . "`";
                                        $SQL2_Vals = "" . quote_smart($field[$i], $db_handle) . "";
                                    } else {
                                        $SQL2_Cols = "";
                                        $SQL2_Vals = "";
                                    }
                                }
                            }
                        } else {
                            $FieldVal = $field[$i];
                            if (strpos($UserExit, "Q") !== false) {
                                //print "<br>FormUpdate.php - *Q* " . $FieldName . " : " . $field[$i] . " : " . $i;
                                if (is_file($UE_Code)) {
                                    //print " - UE_Code found";
                                    $UE_Opts['Exit'] = "Q";
                                    //$UE_Opts['Trace'] = true;
                                    $FieldVal = $UE_Func($ParamRec, $field, $i, $UE_Opts);
                                    //print "<br>FormUpdate.php Q - " . $ParamID . " - FieldVal returned=" . $FieldVal . "<br>";
                                } else {
                                    print " - " . $UE_Code . " not found";
                                }
                            }
                            if ($FieldVal == "" and $Default <> "") {
                                $FieldVal = $Default;
                            }
                            if (strpos($field[$i], "(") == false) {
                                $FieldVal = quote_smart($FieldVal, $db_handle);
                                if ($FieldType == "DATE") {
                                    $FieldVal = "STR_TO_DATE(" . $FieldVal . ", '%d/%m/%Y')";
                                }
                            }
                            if ($num_rows > 0) {
                                if ($i > 1) {
                                    $SQL2 = $SQL2 . ",";
                                }
                                $SQL2 = $SQL2 . " `" . $FieldName . "` = " . $FieldVal;
                            } else {
                                if ($SQL2_Cols <> "") {
                                    $SQL2_Cols = $SQL2_Cols . ",";
                                    $SQL2_Vals = $SQL2_Vals . ",";
                                }
                                $SQL2_Cols = $SQL2_Cols . " `" . $FieldName . "`";
                                $SQL2_Vals = $SQL2_Vals . " " . $FieldVal;
                            }
                        }
                        $i++;
                    }
                }
                if ($num_rows > 0) {
                    $SQL2 = $SQL2 . " WHERE `ID` = " . $ID . "";
                } else {
                    $SQL2 = $SQL2 . "(" . $SQL2_Cols . ") VALUES (" . $SQL2_Vals . ")";
                }
                if ($Trace) {
                    print "<p>FormUpdate.php - SQL2 = " . $SQL2 . "<p>";
                }
                $result2 = mysql_query($SQL2);
                //print "result2 = " . $result2 . ".";
                if ($Action == "I") {
                    $ID = mysql_insert_id();
                }
            }
            if ($Trace) {
                print "<br>FormUpdate.php (end) - Data=";
                var_dump($Data);
            }
            logger($login, $TableName, $ID, $Action);
            fclose($ParamFile);
            if ($Trace) {
                print "<br>FormUpdate.php (after logger) - Data=";
                var_dump($Data);
            }
        } else {
            print $ParamID . "not found!";
        }
        mysql_close($db_handle);
    }
}
header("Location: index.php");
?>